package com.itheima.reggie.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.JwtUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;



@Component // 登录权限拦截器
public class LoginCheckInterceptor implements HandlerInterceptor {

    // 拦截方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String token = request.getHeader("Authorization");
            token = token.replace("Bearer ", "");
            Map map = JwtUtil.parseToken(token);
            /*
                     四个参数介绍
                         map – Map
                         beanClass – Bean Class
                         isToCamelCase – 是否将Map中的下划线风格key转换为驼峰风格
                         copyOptions – 转Bean选项
                  */
            User user = BeanUtil.mapToBean(map, User.class, true, CopyOptions.create());
            UserHolder.set(user);
        } catch (Exception e) {
            e.printStackTrace();
            ResultInfo notlogin = ResultInfo.error("NOTLOGIN");
            String json = JSON.toJSONString(notlogin);
            response.getWriter().write(json);
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
        }
}
